﻿var user;
var autoScroll = true;
chrome.storage.local.get("user",function(item){
	user = item.user;
});
var app = angular.module("myapp", ["firebase"]).config(function ($routeProvider) {
    $routeProvider
        .when('/', {controller: LoginController, templateUrl: 'login.html'})
		.when('/chat',{controller: MyController, templateUrl: 'chat.html'})
		.otherwise({redirectTo: '/'});
});
function MyController($scope,$location, angularFire) {
    $scope.name = user;
	var prefix;
	$scope.messages = [];
	chrome.tabs.getSelected(function(tab){
		if(window.location.href.indexOf("?") > 0){
			prefix = MD5(tab.url.substring(0,tab.url.indexOf("?")));
		}else{
			prefix = MD5(tab.url);
		}
		var ref = new Firebase("https://" + prefix + ".firebaseio-demo.com/");
		angularFire(ref, $scope, "messages");
	});
	$scope.addMessage = function(e) {
	if (e.keyCode != 13) return;
		if($scope.messages.length >= 300){
			$scope.messages.shift(); // remove one message
		}
		$scope.messages.push({from: $scope.name, body: $scope.msg});
		$scope.msg = "";
		document.getElementById("messagesDiv").scrollTop = document.getElementById("messagesDiv").scrollHeight; // auto flow
	}
	
	$scope.changeUser = function(){
		chrome.storage.local.clear();
		$location.path("/")
	}
	refreshScroller();
}

function LoginController($scope, $location ,angularFire){
	$scope.userName = user;
	if(user){
		$location.path("/chat")
	}
	$scope.addGlobal=function (){
		user = $scope.userName;
	}
	$scope.persistUser=function(){
		if($scope.persist == true){
			chrome.storage.local.set({"user":$scope.userName});
		}
		console.log($scope);
	}
}
function refreshScroller(){
	if(autoScroll){
		document.getElementById("messagesDiv").scrollTop = document.getElementById("messagesDiv").scrollHeight; // auto flow
		setTimeout(function(){refreshScroller();}, 300);
	}else{
		setTimeout(function(){refreshScroller();}, 1000);
	}
}

document.onmousedown = function(){
	autoScroll = false;
}

document.onmouseup = function(){
	autoScroll = true;
}

